package model

import (
	"gorm.io/gorm/clause"
)
func init_global(){
	ids:= []string{"redis_url","rt_db","hist_db","redis_psw","frpc_server","frpc_port","frpc_token","log_dir","device_version"}
	names:= []string{"Redis连接地址","Redis实时db","Redis缓存db","Redis密码","frp服务器地址","frp服务器端口","frpc服务器密码","日志目录","配置文件版本号"}
	values:= []string{"127.0.0.1:6379","0","1","","henrywaltz.online","22000","","./","V1.00"}
	for i:=0; i < len(ids); i++{
		kps :=FindKeyPairs(&KeyPair{Id:ids[i]})
		if kps != nil && len(kps) > 0{

		}else{
			kp := KeyPair{
				Id:ids[i],
				Name:names[i],
				Value:values[i],
			}
			kp.Save()
		}
	}
}
type KeyPair struct {
	Id    string 	`xml:"-" json:"id" gorm:"column:id;primary_key;not null;index"`
	Name  string 	`xml:"-" json:"name" gorm:"column:name"`
	Value string    `xml:"-" json:"value" gorm:"column:value"`
}
func FindKeyPairs(filter *KeyPair)[]KeyPair{
	var kps []KeyPair
	if err:=sqldb.Find(&kps,filter).Error;err != nil{
		return nil
	}else{
		return kps
	}
}
func DeleteKeyPairs()(int64,error){
	var kps []KeyPair
	sqldb.Find(&kps)
	index :=0
	for i:=0; i < len(kps); i++{
		if _,err := kps[i].Delete();err != nil{
			return int64(index),err
		}
		index += 1
	}
	return int64(index),nil
}
func (p* KeyPair) Insert()error{
	return sqldb.Create(p).Error
}
func (p* KeyPair) Save()(int64,error){
	ret := sqldb.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "id"}},
		DoUpdates: clause.AssignmentColumns([]string{"name", "value"}),
	}).Create(p)
	return ret.RowsAffected,ret.Error
}
func (p* KeyPair) Delete()(int64,error){
	db :=sqldb.Where(&KeyPair{Id:p.Id}).Delete(&KeyPair{})
	return db.RowsAffected,db.Error
}